<template>
  <el-dialog
    title="编辑班级"
    v-model="dialogVisible"
    width="500px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="班级编号">
        <el-input v-model="form.id" disabled />
      </el-form-item>
      
      <el-form-item label="班级名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入班级名称" />
      </el-form-item>
      
      <el-form-item label="描述">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          placeholder="请输入班级描述"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="'active'"
          :inactive-value="'inactive'"
          active-text="正常"
          inactive-text="停用"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { classService } from '../../services/class'
import { showSuccess, showError } from '../../utils/message'

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref(null)

const form = ref({
  id: '',
  name: '',
  description: '',
  status: 'active'
})

const rules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' }
  ]
}

const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    description: '',
    status: 'active'
  }
  formRef.value?.resetFields()
}

const open = (data) => {
  const { id, name, description, status } = data
  form.value = { 
    id, 
    name, 
    description, 
    status: status || 'active' 
  }
  dialogVisible.value = true
}

const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const result = await classService.updateClass(form.value.id, form.value)
    if (result) {
      showSuccess('修改成功')
      dialogVisible.value = false
      emit('success')
      resetForm()
    }
  } catch (error) {
    showError(error?.message || '修改失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

const emit = defineEmits(['success'])

defineExpose({
  open
})
</script>

<style scoped>
:deep(.el-input),
:deep(.el-textarea) {
  width: 100%;
}
</style>
